package com.wyr.common.aspect;

import com.wyr.common.annotation.RateLimit;
import com.wyr.common.vo.Result;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 限流切面
 *
 * @author wangyiren
 * @version 1.0
 * &#064;title RateLimitAspect
 * &#064;description
 * &#064;date 2025/03/03 09:23
 */
@Slf4j
@Aspect
@Component
public class RateLimitAspect {

    private static final ConcurrentMap<String, RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.wyr.common.annotation.RateLimit)")
    public void rateLimit() {}

    @Around("rateLimit()")
    public Object pointcut(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        RateLimit rateLimiter = AnnotationUtils.findAnnotation(method, RateLimit.class);

        if (rateLimiter != null && rateLimiter.qps() > RateLimit.NOT_LIMITED) {
            double qps = rateLimiter.qps();

            // 线程安全的更新限流器
            RATE_LIMITER_CACHE.compute(method.getName(), (key, existingLimiter) -> {
                if (existingLimiter == null || existingLimiter.getRate() != qps) {
                    return RateLimiter.create(qps);
                }
                return existingLimiter;
            });

            log.debug("【{}】的QPS设置为: {}", method.getName(), RATE_LIMITER_CACHE.get(method.getName()).getRate());

            // 尝试获取令牌
            if (!RATE_LIMITER_CACHE.get(method.getName()).tryAcquire(rateLimiter.timeout(), rateLimiter.timeUnit())) {
                log.warn("!!!!!!!!!被限流啦");
                return Result.error("请求达到峰值被限流了,请稍后重试");
            }
        }

        return point.proceed();
    }
}
